package com.sofwin.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sofwin.Constants;
import com.sofwin.dto.SUserDto;
import com.sofwin.pojo.SDept;
import com.sofwin.pojo.SRole;
import com.sofwin.pojo.SUser;
import com.sofwin.service.SDeptService;
import com.sofwin.service.SRoleService;
import com.sofwin.service.SUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 请求数据
 */
@Controller
@RequestMapping("system/user")
public class UserController {

    @Autowired
    private SUserService userService;
    @Autowired
    private SDeptService deptService;
    @Autowired
    private SRoleService roleService;

    @RequestMapping("data")
    public String data(SUser user, @RequestParam(required = true,defaultValue = "1") Integer pageNumber,@RequestParam(required = true,defaultValue = Constants.DEFAULT_PAGE_SIZE) Integer pageSize,
                       Model model){
        PageHelper.startPage(pageNumber,pageSize);
        PageInfo<SUserDto> pageInfo = userService.selectUsers(user,pageNumber,pageSize);
        model.addAttribute("page",pageInfo);
        model.addAttribute("data",pageInfo.getList());
        model.addAttribute("user",user);
        return "user/data";
    }

    @RequestMapping("deletes")
    @ResponseBody
    public Map deletes(Integer[] ids){
        boolean status = userService.deletesByIds(ids);
        Map map = new HashMap<>();
        map.put("status",status);
        return map;
    }

    @GetMapping(value = "toEdit")
    public String toEdit(Model model,Integer id){
        // 查询数据库获得部门名称
        List<SDept> depts = deptService.getDeptNames();
        // 查询数据库获得角色名称
        List<SRole> roles = roleService.getRoleNames();
        model.addAttribute("depts",depts);
        model.addAttribute("roles",roles);
        if (id != null){
            SUser user = userService.selectUserById(id);
            model.addAttribute("user",user);
        }
        return "user/edit";
    }

    @RequestMapping("save")
    @ResponseBody
    public Map save(SUser user){
        boolean status = userService.insertUser(user);
        Map map = new HashMap();
        map.put("status",status);
        return map;
    }

}
